package rpc;

//rpc服务器，负责接受请求和回复响应


import com.rabbitmq.client.*;
import contants.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RpcServer {

    public static void main(String[] args) throws IOException, TimeoutException {
        //1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);//主机ip
        factory.setPort(Constants.PORT);//端口号
        factory.setUsername(Constants.USER_NAME);//用户名
        factory.setPassword(Constants.PASSWORD);//用户密码
        factory.setVirtualHost(Constants.VIRTUAL_HOST);//虚拟主机
        Connection connection = factory.newConnection();
        //2.开启信道
        Channel channel = connection.createChannel();
        //3.接受请求并返回响应
        channel.basicQos(1);//每次接受一个请求
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String request = new String(body,"UTF-8");
                System.out.println("接收到请求:"+ request);
                String response = "针对request:"+ request +", 响应成功";
                AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("", Constants.RPC_RESPONSE_QUEUE, basicProperties, response.getBytes());//返回响应
                channel.basicAck(envelope.getDeliveryTag(), false);//手动确认
            }
        };
        channel.basicConsume(Constants.RPC_REQUEST_QUEUE,false,consumer);
    }
}
